import pandas as pd
from gypb.component import DDBUploader
from dash import register_page

register_page(__name__, name="净值上传", order=7)

def nav_parser(df: pd.DataFrame) -> pd.DataFrame:
    df = df[
        ["产品简称", "产品编码", "净值日期", "最新净值", "累计净值"]
    ].drop_duplicates(subset=["产品编码", "净值日期"], keep="last")[:-1]

    try:
        df.rename(
            columns={
                "净值日期": "datetime",
                "产品编码": "code",
                "最新净值": "netvalue",
                "累计净值": "cum_netvalue",
            },
            inplace=True,
        )
        df = df[["code", "datetime", "netvalue", "cum_netvalue"]].copy()
        df["datetime"] = pd.to_datetime(df["datetime"], format="%Y%m%d")

        df = df.set_index(["code", "datetime"]).stack().reset_index(level=2)
        df.columns = ["attribute", "value"]
        return df
    except Exception as e:
        return e
    
nav_excel_uploader = DDBUploader(
    name="otcnav_upload",
    db_path="dfs://product_daily",
    table_name = "attr_double",
    key_cols=["datetime", "code"],
    cache_dir=None,
    parser=nav_parser,
    header=8,
)

layout = nav_excel_uploader.layout